<?php

class AdminFicheController extends ModuleAdminController {

	protected function storeSizeAllSubmit($modulator)
	{
		if ( isset($_POST['storeSizeAllSubmit']) && !empty($_POST['storeSizeAllSubmit']) )
		{
			$list = explode(',', $_POST['actionList']);
			$store = ceil((float)($_POST['storeSizeAll']) * $modulator);
			
			foreach( $list as $value )
			{
				$abo = FicheAbo::getFicheAbo((int)($value));
				
				if ( $abo != null )
				{
					$abo->storeSize = $store;
					$abo->update();
				}
			}
		}
	}

	protected function connectAsUser()
	{
		if ( isset($_GET['login']) && !empty($_GET['login']) && isset($_GET['id_customer']) )
		{
			$link = new Link();
			$linkModule = $link->getModuleLink('fichevitrine', 'default');
			if ( !isset($_SESSION) )
			{
				session_start();
			}
			
			$_SESSION['id_customer'] = (int)($_GET['id_customer']);
			$_SESSION['adminKey'] = Configuration::get('fichevitrine_adminKey_');
			Tools::redirect($linkModule.'?loginAsCustomer=1');
		}
	}
	
	protected function searchUserBy()
	{
		$result = array();
		$sql = 'SELECT id_customer, firstname, lastname, email, company FROM '. _DB_PREFIX_ . 'customer';
		$i = 0;
		
		if ( isset($_POST['searchUser']) && !empty($_POST['searchUser']) )
		{
			if ( isset($_POST['company']) && !empty($_POST['company']) )
			{
				$sql .= ($i == 0)? ' WHERE' : ' AND';	$i++;
				$sql .= ' company = "'.$_POST['company'].'"';
			}
			
			if ( isset($_POST['firstname']) && !empty($_POST['firstname']) )
			{
				$sql .= ($i == 0)? ' WHERE' : ' AND';	$i++;
				$sql .= ' firstname = "'.$_POST['firstname'].'"';
			}
			
			if ( isset($_POST['lastname']) && !empty($_POST['lastname']) )
			{
				$sql .= ($i == 0)? ' WHERE' : ' AND';	$i++;
				$sql .= ' lastname = "'.$_POST['lastname'].'"';
			}

			$result = Db :: getInstance()->ExecuteS($sql);
		}
		
		return $result;
	}
	
	protected function createUser()
	{
		if ( isset($_POST['createUser']) && !empty($_POST['createUser']) )
		{
			$list = Customer::getCustomersByEmail($_POST['userEmail']);
			foreach( $list as $value )
			{
				FicheAbo::getFicheAbo((int)($value['id_customer']));
			}
		}
	}
	
	protected function saveConfig()
	{
		if ( isset($_POST['saveConfig']) && !empty($_POST['saveConfig']) )
		{
			Configuration::updateValue('fichevitrine_autoSaveTime_', (int)($_POST['autoSaveTime']));
			Configuration::updateValue('fichevitrine_autoSave_', (int)($_POST['autoSave']));
			Configuration::updateValue('fichevitrine_fontList_', $_POST['fontList']);
			Configuration::updateValue('fichevitrine_fontSizeStart_', (int)($_POST['startSize']));
			Configuration::updateValue('fichevitrine_fontSizeEnd_', (int)($_POST['endSize']));
		}
	}
	
	protected function addTheme()
	{
		if ( isset($_POST['addTheme']) && !empty($_POST['addTheme']) )
		{
			FicheTheme::addTheme($_POST['themeName']);
		}
	}
	
	protected function killTheme()
	{
		if ( isset($_POST['deleteTheme']) && !empty($_POST['deleteTheme']) )
		{
			FicheTheme::killThemeById((int)($_GET['id_theme']));
		}
		
	}
	
	protected function addProp()
	{
		if ( isset($_POST['addProp']) && !empty($_POST['addProp']) )
		{
			FicheProp::addProp($_POST['propName']);
		}
	}
	
	protected function killProp()
	{
		if ( isset($_POST['deleteProp']) && !empty($_POST['deleteProp']) )
		{
			FicheProp::killPropById((int)($_GET['id_prop']));
		}
		
	}
	
	protected function saveAbo($modulator)
	{
		if ( isset($_POST['saveAbo']) && !empty($_POST['saveAbo']) )
		{
			$abo = FicheAbo::getFicheAbo((int)($_POST['id_customer']));
			if ( $abo != null )
			{
				$abo->date_start = $_POST['date_start'];
				$abo->date_end = $_POST['date_end'];
				$abo->storeSize = ceil((float)($_POST['storeSize']) * $modulator);
				$abo->twoInOne = (int)($_POST['twoInOne']);
				$abo->update();
			}
		}
	}
	
	protected function getStats()
	{
		$results = array();
		$results['accounts'] = array();
		$results['fiches'] = array();
		
		$conditions = array();
		$date_start = date('Y-m-d 00:00:00', time());
		$date_end = date('Y-m-d H:i:s', time() + ( 24 * 365 * 60 * 60 ) );
		
		if ( isset($_POST['show_stats']) && !empty($_POST['show_stats']) )
		{
			$date_start = $_POST['date_stats_start'];
			$date_end = $_POST['date_stats_end'];
		}
			
		$conditions['date_start'] = array('column' => 'date', 'value' => $date_start, 'operator' => '>=');
		$conditions['date_end'] = array('column' => 'date', 'value' => $date_end, 'operator' => '<=');
		
		$fiches = Fiche::findFicheBy($conditions, -1, -1, 'date', true, false);
			
		$conditions['date_start'] = array('column'=>'date_start', 'value'=>$date_start, 'operator'=>'>=');
		$conditions['date_end'] = array('column'=>'date_start', 'value'=>$date_end, 'operator'=>'<=');
		$accounts = FicheAbo::findAboBy($conditions, -1, -1, 'date_start', true);
			
		$results['accounts'] = $accounts;
		$results['fiches'] = $fiches;
		$results['date_start'] = $date_start;
		$results['date_end'] = $date_end;
		
		return $results;
	}
	
	
	public function __construct() 
	{
		parent::__construct();
		
		$modulator = 1024 * 1024;
		$link = new Link();
		
		$result = $this->searchUserBy();
		$this->addTheme();
		$this->killTheme();
		$this->addProp();
		$this->killProp();
		$this->connectAsUser();
		$this->createUser();
		$this->saveConfig();
		$this->saveAbo($modulator);
		$this->storeSizeAllSubmit($modulator);
	
		
		$ficheLink = $link->getAdminLink('AdminFiche', true);
		$customersLink = $link->getAdminLink('AdminCustomers', true);
		$linkModule = $link->getModuleLink('fichevitrine', 'default');
		
		$autoSaveTime 		= Configuration::get('fichevitrine_autoSaveTime_');
		$autoSave 			= Configuration::get('fichevitrine_autoSave_');
		$fontList 			= Configuration::get('fichevitrine_fontList_');
		$startSize 			= Configuration::get('fichevitrine_fontSizeStart_');
		$endSize 			= Configuration::get('fichevitrine_fontSizeEnd_');
		$jsDir				= _MODULE_DIR_.'fichevitrine/js/';
		
		
		$conditions = array();
		
		if ( isset($_POST['f_searchAccount']) )
		{
			
			if ( isset($_POST['f_accountSurname']) && !empty($_POST['f_accountSurname']) ) 
				$conditions["customer_lastname"] = array("operator"=>"LIKE","column"=>$_POST['f_accountSurname']);
				
			if ( isset($_POST['f_accountName'])  && !empty($_POST['f_accountName']) ) 
				$conditions["customer_firstname"] = array("operator"=>"LIKE","column"=>$_POST['customer_firstname']);
				//$conditions["customer_firstname"] = $_POST['f_accountName'];
				
			
			if ( isset($_POST['f_accountMail'])  && !empty($_POST['f_accountMail']) ) 
				$conditions["customer_email"] = array("operator"=>"LIKE","column"=>$_POST['customer_email']);
				//$conditions["customer_email"] = $_POST['f_accountMail'];
				
				
		}
		
		$resultsPerPage 	= 15;
		$numPages = ceil( FicheAbo::getTotalAboWhere($conditions) / $resultsPerPage ) - 1;
		$currentPage = (isset($_GET['page'])) ? (int)($_GET['page']) : 0;
		$currentPage = ( $currentPage > $numPages ) ? $numPages : $currentPage;
		$currentPage = ( $currentPage < 0 ) ? 0 : $currentPage;
		
		$start = $currentPage * $resultsPerPage;
		$end = $resultsPerPage;
		
		$aboList 			= FicheAbo::findAboBy($conditions, $start, $end);
	
		foreach( $aboList as $abo )
		{
			$abo->storeSize /= $modulator;
		}
		
		
		$stats = $this->getStats();
		
		$this->context->smarty->assign(array(
			'props' => FicheProp::findAll(),
			'themes' => FicheTheme::findAll(),
			'date_stats_start' => $stats['date_start'],
			'date_stats_end' => $stats['date_end'],
			'statsFiches' => json_encode($stats['fiches']),
			'statsAccounts' => json_encode($stats['accounts']),
			'ficheLink' => $ficheLink,
			'customersLink' => $customersLink,
			'jsDir' => $jsDir,
			'aboList' => $aboList,
			'currentPage' => $currentPage,
			'numPagesAbo' => $numPages,
			'autoSave' => $autoSave,
			'autoSaveTime' => $autoSaveTime,
			'linkModule'=>$linkModule,
			'fontList'=>$fontList,
			'startSize'=>$startSize,
			'result'=>$result,
			'endSize'=>$endSize
		));
		
		$this->setTemplate('adminfiche.tpl');
	}
	

	//override this stupid behavior of prestashop...
	public function createTemplate($tpl_name)
    {
		$path = _PS_MODULE_DIR_.$this->module->name.'/views/templates/admin/';
		$tpl = $path.$tpl_name;
        
        if (file_exists($tpl) && $this->viewAccess())
            return $this->context->smarty->createTemplate($tpl, $this->context->smarty);

        return parent::createTemplate($tpl_name);
    }
	
}